#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unordered_map>
#include <memory>
#include <jsoncpp/json/json.h>
#include <vector>
#include "Protocol.hpp"
#include "bcrypt.hpp"
#include "Log.hpp"
#include "Init.hpp"
#include "MySQL.hpp"
#include "Tools.hpp"
extern Log lg;

enum
{
    REGISTE = 1,
    LOGIN,
    RESERVATION,
    MYRESERVATION,
    INCAR,
    OUTCAR,
    CHECKSPOT,
    SEARCHSPOT,
    PARKINGRECORD, // 9
    PAYMENT,
    CURRENTSTATISTIC,
    PREVIOUSSTATISTIC,
};

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : sockfd_(sockfd), clientip_(clientip), clientport_(clientport)
    {
        sql_ = std::make_unique<SQL>();
        sql_->connectSQL(); // 每个任务独立连接
    }

    Task()
    {
    }

    // 移动构造 & 赋值（由编译器生成）
    Task(Task &&) noexcept = default;
    Task &operator=(Task &&) noexcept = default;

    //  禁用拷贝构造和拷贝赋值
    Task(const Task &) = delete;
    Task &operator=(const Task &) = delete;

    void run()
    {
        // testsql();
        // testJson();
        funcChoice();
    }

    void funcChoice();
    void testsql();
    void testJson();
    int getAvailableSpot(std::string &location);

    // windows端功能对应接口
    void inCar(Json::Value message);
    void outCar(Json::Value message);
    void checkSpot(Json::Value message);
    void searchSpot(Json::Value message);
    void parkingRecord(Json::Value message);
    void payment(Json::Value message);
    void currentStatistic(Json::Value message);
    void previousStatistic(Json::Value message);

    // 安卓端功能对应接口
    void registe(Json::Value message);
    void login(Json::Value message);
    void reservation(Json::Value message);
    void myreservation(Json::Value message);

    void operator()()
    {
        run();
    }

    ~Task()
    {
    }

private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
    // SQL sql_;
    std::unique_ptr<SQL> sql_;
};

void Task::funcChoice()
{
    bool isRunning = true;
    while (isRunning)
    {
        char buffer[4096];
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            // std::cout << "get message:" << buffer << std::endl;
            std::string package(buffer);
            std::string content;
            bool b = Decode(package, &content);
            if (!b)
                return;

            Json::Value root;
            Json::Value message;
            Json::Reader r;
            r.parse(content, root);

            int func = root["func"].asInt();
            message = root["message"];

            switch (func)
            {
            case REGISTE:
                registe(message);
                break;
            case LOGIN:
                login(message);
                break;
            case RESERVATION:
                reservation(message);
                break;
            case MYRESERVATION:
                myreservation(message);
                break;
            case INCAR:
                inCar(message);
                break;
            case OUTCAR:
                outCar(message);
                break;
            case CHECKSPOT:
                checkSpot(message);
                break;
            case SEARCHSPOT:
                searchSpot(message);
                break;
            case PARKINGRECORD:
                parkingRecord(message);
                break;
            case PAYMENT:
                payment(message);
                break;
            case CURRENTSTATISTIC:
                currentStatistic(message);
                break;
            case PREVIOUSSTATISTIC:
                previousStatistic(message);
                break;
            default:
                break;
            }
        }
        else if (n == 0)
        {
            isRunning = false;
            lg(Info, "%s:%d quit,server close sockfd:%d", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            lg(Warning, "read error,sockfd:%d,client ip:%s,client port:%d", sockfd_, clientip_.c_str(), clientport_);
        }
    }
    close(sockfd_);
}

void Task::testsql()
{
    bool isRunning = true;
    while (isRunning)
    {
        char buffer[4096];
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get message:" << buffer << std::endl;
            std::string str(buffer);
            std::string query = "INSERT INTO message (message) VALUES ('" + str + "')";
            int sql_n = mysql_query(sql_->my_, query.c_str());
            std::string echo_string;
            if (sql_n == 0)
            {
                echo_string = "已经向数据库插入信息：";
                echo_string += buffer;
            }
            else
            {
                echo_string = "向数据库插入信息失败";
            }

            int n2 = write(sockfd_, echo_string.c_str(), echo_string.size());
            if (n2 < 0)
            {
                lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
                return;
            }
            lg(Info, "已向数据库中插入一条信息，信息为：%s", buffer);
        }
        else if (n == 0)
        {
            isRunning = false;
            lg(Info, "%s:%d quit,server close sockfd:%d", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            lg(Warning, "read error,sockfd:%d,client ip:%s,client port:%d", sockfd_, clientip_.c_str(), clientport_);
        }
    }
    close(sockfd_);
}

void Task::testJson()
{
    bool isRunning = true;
    while (isRunning)
    {
        char buffer[4096];
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::string package(buffer);
            std::string content;
            // std::cout<<package<<std::endl;
            // std::cout<<content<<std::endl;

            bool b = Decode(package, &content);
            // std::cout<<b<<std::endl;
            if (!b)
                return;

            Json::Value root;
            Json::Value message;
            Json::Reader r;
            r.parse(content, root);
            std::string func = root["func"].asString();
            // std::string message = root["func"].asString();
            // std::cout << "get func: " << func << "get message:" << message << std::endl;
            message = root["message"];

            // std::string plate = message["plate"].asString();
            // std::string time = message["time"].asString();

            std::string password = message["password"].asString();
            std::string username = message["username"].asString();
            if (func == "1")
            {
                // func1();
                // std::cout<<"plate:"<<plate<<"  time: "<<time<<std::endl;
            }
            else if (func == "2")
            {
                std::cout << "password:" << password << "  username: " << username << std::endl;
            }
        }
        else if (n == 0)
        {
            isRunning = false;
            lg(Info, "%s:%d quit,server close sockfd:%d", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            lg(Warning, "read error,sockfd:%d,client ip:%s,client port:%d", sockfd_, clientip_.c_str(), clientport_);
        }
    }
    close(sockfd_);
}

// 获取一个空车位的id
int Task::getAvailableSpot(std::string &location)
{
    std::string query = "SELECT spot_id, location FROM Parking_Spot WHERE status = 'available' LIMIT 1";
    int n = mysql_query(sql_->my_, query.c_str());
    if (n == 0)
    {
        lg(Info, "getAvailableSpot success");
    }
    else
    {
        lg(Error, "getAvailableSpot failed,%d", mysql_error(sql_->my_));
        return -1;
    }
    MYSQL_RES *res;
    MYSQL_ROW row;
    res = mysql_store_result(sql_->my_);
    if (res == nullptr)
    {
        lg(Error, "getAvailableSpot failed,%d", mysql_error(sql_->my_));
        return -1;
    }
    int spot_id = -1;
    if ((row = mysql_fetch_row(res)))
    {
        spot_id = atoi(row[0]); // 获取 spot_id
        location = row[1];
    }
    mysql_free_result(res);
    return spot_id;
}

void Task::inCar(Json::Value message)
{
    std::string plate = message["plate"].asString();
    std::string entry_time = message["time"].asString();
    lg(Info, "get one incar: plate: %s, time: %s", plate.c_str(), entry_time.c_str());

    MYSQL_RES *res;
    MYSQL_ROW row;

    bool isInVehicle = false;
    bool isReserved = false;
    int vehicle_id = -1;
    int spot_id = -1;

    // 判断是否在Vehicle表中
    std::string selectVehicle = "SELECT vehicle_id FROM Vehicle WHERE plate = '" + plate + "'";
    if (mysql_query(sql_->my_, selectVehicle.c_str()) == 0)
    {
        res = mysql_store_result(sql_->my_);
        if ((row = mysql_fetch_row(res)) != nullptr)
        {
            vehicle_id = atoi(row[0]);
            isInVehicle = true;
        }
    }
    else
    {
        std::cerr << "SELECT Vehicle failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    if (isInVehicle)
    {
        // Reservation 是否有可用预约
        std::string selectReservation = "SELECT spot_id FROM Reservation WHERE vehicle_id = " + std::to_string(vehicle_id) + " AND status = 'available'";
        if (mysql_query(sql_->my_, selectReservation.c_str()) == 0)
        {
            res = mysql_store_result(sql_->my_);
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                isReserved = true;
                spot_id = atoi(row[0]);
            }
        }
        else
        {
            std::cerr << "SELECT Reservation failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }

        if (isReserved)
        {
            // 有预约，更新 Reservation 为 used
            std::string updateRes = "UPDATE Reservation SET status = 'used' WHERE vehicle_id = " + std::to_string(vehicle_id);
            if (mysql_query(sql_->my_, updateRes.c_str()) != 0)
            {
                std::cerr << "UPDATE Reservation failed: " << mysql_error(sql_->my_) << std::endl;
                return;
            }
        }
        else
        {
            // 2.2 无预约，获取可用车位
            std::string location;
            spot_id = getAvailableSpot(location);
            if (spot_id == -1)
            {
                std::cerr << "获取可用车位失败" << std::endl;
                return;
            }
        }

        // 更新 Parking_Spot 状态
        std::string updateSpot = "UPDATE Parking_Spot SET status = 'occupied' WHERE spot_id = " + std::to_string(spot_id);
        if (mysql_query(sql_->my_, updateSpot.c_str()) != 0)
        {
            std::cerr << "UPDATE Parking_Spot failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }

        // 更新 Vehicle 状态为 in
        std::string updateVehicle = "UPDATE Vehicle SET status = 'in' WHERE vehicle_id = " + std::to_string(vehicle_id);
        if (mysql_query(sql_->my_, updateVehicle.c_str()) != 0)
        {
            std::cerr << "UPDATE Vehicle failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }
    }
    else
    {
        // 是新车，先插入 Vehicle 表
        std::string insertVehicle = "INSERT INTO Vehicle (plate) VALUES ('" + plate + "')";
        if (mysql_query(sql_->my_, insertVehicle.c_str()) == 0)
        {
            vehicle_id = static_cast<int>(mysql_insert_id(sql_->my_));
            std::cout << "插入新车成功，vehicle_id: " << vehicle_id << std::endl;
        }
        else
        {
            std::cerr << "插入新车失败: " << mysql_error(sql_->my_) << std::endl;
            return;
        }

        // 获取空车位
        std::string tmp;
        spot_id = getAvailableSpot(tmp);
        if (spot_id == -1)
        {
            std::cerr << "获取可用车位失败" << std::endl;
            return;
        }

        // 更新车位状态
        std::string updateSpot = "UPDATE Parking_Spot SET status = 'occupied' WHERE spot_id = " + std::to_string(spot_id);
        if (mysql_query(sql_->my_, updateSpot.c_str()) != 0)
        {
            std::cerr << "UPDATE Parking_Spot failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }

        // 更新新车状态为 in
        std::string updateVehicle = "UPDATE Vehicle SET status = 'in' WHERE vehicle_id = " + std::to_string(vehicle_id);
        if (mysql_query(sql_->my_, updateVehicle.c_str()) != 0)
        {
            std::cerr << "UPDATE Vehicle failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }
    }

    // 插入 Parking_Record 表
    std::string insertRecord = "INSERT INTO Parking_Record (vehicle_id, spot_id, entry_time) VALUES (" +
                               std::to_string(vehicle_id) + ", " + std::to_string(spot_id) + ", '" + entry_time + "')";
    if (mysql_query(sql_->my_, insertRecord.c_str()) == 0)
    {
        std::cout << "插入 Parking_Record 成功" << std::endl;
    }
    else
    {
        std::cerr << "插入 Parking_Record 失败: " << mysql_error(sql_->my_) << std::endl;
    }

    std::string location;
    std::string selectLocation = "SELECT location FROM Parking_Spot WHERE spot_id = " + std::to_string(spot_id);
    if (mysql_query(sql_->my_, selectLocation.c_str()) == 0)
    {
        res = mysql_store_result(sql_->my_);
        if ((row = mysql_fetch_row(res)) != nullptr)
        {
            location = row[0];
        }
        else
        {
            std::cerr << "未找到对应车位的 location" << std::endl;
        }
    }
    else
    {
        std::cerr << "查询 Parking_Spot 的 location 失败: " << mysql_error(sql_->my_) << std::endl;
    }

    Json::Value root;
    Json::Value message1;
    Json::Value message2;
    Json::FastWriter w;
    if (isReserved)
    {
        message2["isReserved"] = 1;
    }
    else
    {
        message2["isReserved"] = 0;
    }
    message2["location"] = location;

    message1["func2"] = 1;
    message1["message2"] = message2;
    root["func"] = 1;
    root["message"] = message1;
    std::string content = w.write(root);
    std::string package = Encode(content);
    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
        return;
    }
}

void Task::outCar(Json::Value message)
{
    std::string plate = message["plate"].asString();
    std::string exit_time = message["time"].asString();
    lg(Info, "outcar,plate:%s ,exit_time:%s", plate.c_str(), exit_time.c_str());

    MYSQL_RES *res;
    MYSQL_ROW row;
    Json::Value root;
    Json::Value message1;
    Json::Value message2;
    Json::FastWriter w;
    bool isIn = false;
    int vehicle_id = -1;
    std::string query = "SELECT vehicle_id, status FROM Vehicle WHERE plate = '" + plate + "'";
    if (mysql_query(sql_->my_, query.c_str()) != 0)
    {
        std::cerr << "查询 Vehicle 表失败: " << mysql_error(sql_->my_) << std::endl;
    }
    else
    {
        res = mysql_store_result(sql_->my_);
        row = mysql_fetch_row(res);

        if (row != nullptr)
        {
            std::string status = row[1];
            if (status == "in")
            {
                isIn = true;
                vehicle_id = atoi(row[0]);
            }
            else
            {
                isIn = false;
                vehicle_id = atoi(row[0]);
            }
        }
        else
        {
            isIn = false;
        }
    }

    if (!isIn)
    {
        lg(Info, "%s is not in the park", plate.c_str());
        message2["isIn"] = 0;
        message1["func2"] = 2;
        message1["message2"] = message2;
        root["func"] = 1;
        root["message"] = message1;
        std::string content = w.write(root);
        std::string package = Encode(content);
        int n = write(sockfd_, package.c_str(), package.size());
        if (n < 0)
        {
            lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
            return;
        }
        return;
    }
    else
    {
        int record_id = -1;
        int spot_id = -1;
        std::string entry_time;
        lg(Info, "%s is in the park,vehicle_id: %d", plate.c_str(), vehicle_id);
        query = "SELECT record_id, spot_id, entry_time FROM Parking_Record  WHERE vehicle_id = " + std::to_string(vehicle_id) + " AND status = 'ongoing'";
        if (mysql_query(sql_->my_, query.c_str()) == 0)
        {
            res = mysql_store_result(sql_->my_);
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                if (row[0])
                    record_id = atoi(row[0]);
                if (row[1])
                    spot_id = atoi(row[1]);
                if (row[2])
                    entry_time = row[2];
                lg(Info, "outCar,found ongoing record - record_id: %d,spot_id: %d, entry_time: %s", record_id, spot_id, entry_time.c_str());
            }
            else
            {
                lg(Info, "outCar, no ongoing record found for vehicle_id: %d", vehicle_id);
            }
        }
        else
        {
            std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }

        std::string updateStatusQuery = "UPDATE Vehicle SET status = 'out' WHERE vehicle_id = " + std::to_string(vehicle_id);
        if (mysql_query(sql_->my_, updateStatusQuery.c_str()) != 0)
        {
            std::cerr << "UPDATE Vehicle status to 'out' failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }
        else
        {
            std::cout << "Vehicle status updated to 'out' successfully." << std::endl;
        }

        std::string updateSpotStatusQuery = "UPDATE Parking_Spot SET status = 'available' WHERE spot_id = " + std::to_string(spot_id);
        if (mysql_query(sql_->my_, updateSpotStatusQuery.c_str()) != 0)
        {
            std::cerr << "UPDATE Parking_Spot status to 'available' failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }
        else
        {
            std::cout << "Parking_Spot status updated to 'available' successfully." << std::endl;
        }

        // 计算时间和费用
        int secondsDifference = computeTimeDifference(entry_time, exit_time);
        std::cout << "secondsDifference:" << secondsDifference << std::endl;
        int hours = secondsDifference / 3600;
        int mins = (secondsDifference % 3600) / 60;
        int secs = secondsDifference % 60;
        double fee = calculateParkingFee(secondsDifference);
        lg(Info, "outCar,Parking duration:%d hours,%d mins,%d secs, fee:%f", hours, mins, secs, fee);

        std::string updateRecordQuery =
            "UPDATE Parking_Record SET exit_time = '" + exit_time +
            "', fee = " + std::to_string(fee) +
            ", status = 'done' WHERE record_id = " + std::to_string(record_id);

        if (mysql_query(sql_->my_, updateRecordQuery.c_str()) != 0)
        {
            std::cerr << "UPDATE Parking_Record failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }
        else
        {
            std::cout << "Parking_Record updated successfully: record_id = " << record_id << std::endl;
        }
        std::string insertPayQuery = "INSERT INTO Payment (record_id,payment_time,amount) VALUES(" + std::to_string(record_id) + ",'" + exit_time + "'," + std::to_string(fee) + ")";
        if (mysql_query(sql_->my_, insertPayQuery.c_str()) != 0)
        {
            std::cerr << "INSERT INTO Payment failed: " << mysql_error(sql_->my_) << std::endl;
            return;
        }
        else
        {
            std::cout << "Payment record inserted successfully for record_id = " << record_id << std::endl;
        }
        message2["hours"] = hours;
        message2["mins"] = mins;
        message2["secs"] = secs;
        message2["fee"] = fee;
        message2["isIn"] = 1;
        message1["func2"] = 2;
        message1["message2"] = message2;

        root["func"] = 1;
        root["message"] = message1;
        std::string content = w.write(root);
        std::string package = Encode(content);
        int n = write(sockfd_, package.c_str(), package.size());
        if (n < 0)
        {
            lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
            return;
        }
    }
}

void Task::checkSpot(Json::Value message)
{
    int signal = message["signal"].asInt();
    // std::cout<<"signal:  "<<signal<<std::endl;
    std::vector<int> statusArray;
    std::string query = "SELECT status FROM Parking_Spot ORDER BY spot_id";
    if (mysql_query(sql_->my_, query.c_str()) == 0)
    {
        MYSQL_RES *res = mysql_store_result(sql_->my_);
        MYSQL_ROW row;

        while ((row = mysql_fetch_row(res)))
        {
            std::string status = row[0];
            if (status == "available")
            {
                statusArray.push_back(0);
            }
            else if (status == "reserved")
            {
                statusArray.push_back(1);
            }
            else if (status == "occupied")
            {
                statusArray.push_back(2);
            }
            else
            {
                statusArray.push_back(-1);
            }
        }
        mysql_free_result(res);
    }
    else
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }

    // std::vector<int>::iterator it = statusArray.begin();
    // while (it != statusArray.end())
    // {
    //     std::cout << *it << " ";
    //     it++;
    // }
    // std::cout << std::endl;

    Json::Value root;
    Json::Value message1;
    Json::Value message2;
    Json::StreamWriterBuilder writer;
    root["func"] = 2;

    if (signal == 1)
    {
        message1["func2"] = 1;
    }
    else
    {
        message1["func2"] = 2;
    }

    Json::Value statusJsonArray;
    for (const auto &status : statusArray)
    {
        statusJsonArray.append(status);
    }
    message2["vector"] = statusJsonArray;

    message1["message2"] = message2;
    root["message"] = message1;
    std::string content = Json::writeString(writer, root);
    std::string package = Encode(content);

    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
        return;
    }
}

void Task::searchSpot(Json::Value message)
{
    Json::Value root;
    Json::Value message1;
    Json::Value message2;
    Json::FastWriter w;
    std::string location = message["spot"].asString();
    // std::cout<<spot<<std::endl;
    std::string query = "SELECT spot_id, status FROM Parking_Spot WHERE location='" + location + "'";
    if (mysql_query(sql_->my_, query.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << "\n";
    }
    MYSQL_RES *res = mysql_store_result(sql_->my_);
    MYSQL_ROW row;
    std::string status;
    int spot_id;
    if ((row = mysql_fetch_row(res)))
    {
        spot_id = std::stoi(row[0]);
        status = row[1];
    }
    std::cout << "spot_id: " << spot_id << " status:" << status << std::endl;

    root["func"] = 2;
    message1["func2"] = 3;
    if (status == "occupied")
    {
        query = "SELECT v.plate "
                "FROM Parking_Record p "
                "JOIN Vehicle v ON p.vehicle_id = v.vehicle_id "
                "WHERE p.spot_id = " +
                std::to_string(spot_id) + " "
                                          "AND p.status = 'ongoing'";

        std::string plate;
        if (mysql_query(sql_->my_, query.c_str()) == 0)
        {
            res = mysql_store_result(sql_->my_);
            if ((row = mysql_fetch_row(res)))
            {
                // row[0] 可能是 NULL
                plate = (row[0] != nullptr) ? row[0] : "";
                std::cout << "Plate found: " << plate << std::endl;
            }
            else
            {
                std::cout << "No vehicle found for spot_id = " << spot_id << std::endl;
            }
        }
        else
        {
            std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        }
        message2["status"] = "occupied";
        message2["plate"] = plate;
        // std::cout<<plate<<std::endl;
    }
    else if (status == "reserved")
    {
        query = "SELECT v.plate "
                "FROM Reservation r "
                "JOIN Vehicle v ON r.vehicle_id = v.vehicle_id "
                "WHERE r.status = 'available' AND r.spot_id = " +
                std::to_string(spot_id) + ";";
        std::string plate;
        if (mysql_query(sql_->my_, query.c_str()) == 0)
        {

            res = mysql_store_result(sql_->my_);
            if ((row = mysql_fetch_row(res)))
            {
                plate = (row[0] != nullptr) ? row[0] : "";
                std::cout << "Reservation Plate found: " << plate << std::endl;
            }
            else
            {
                std::cout << "No reservation found for spot_id = " << spot_id << std::endl;
            }
        }
        else
        {
            std::cerr << "Reservation Query failed: " << mysql_error(sql_->my_) << std::endl;
        }

        message2["status"] = "reserved";
        message2["plate"] = plate;
        // std::cout<<plate<<std::endl;
    }
    else
    {
        std::string plate;
        message2["status"] = "available";
        message2["plate"] = plate;
    }
    mysql_free_result(res);
    message1["message2"] = message2;
    root["message"] = message1;
    std::string content = w.write(root);
    std::string package = Encode(content);

    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
        return;
    }
}

void Task::parkingRecord(Json::Value message)
{
    int lines = message["n"].asInt();          // 缓存文件中，正在进行中的行数
    int totalLines = message["total"].asInt(); // 缓存文件中，总行数
    std::cout << "lines:" << lines << std::endl;
    std::string query_ = "SELECT COUNT(*) FROM Payment;";
    if (mysql_query(sql_->my_, query_.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }

    MYSQL_RES *res_ = mysql_store_result(sql_->my_);
    if (!res_)
    {
        std::cerr << "Store result failed: " << mysql_error(sql_->my_) << std::endl;
    }

    MYSQL_ROW row_ = mysql_fetch_row(res_);
    int dbLines = (row_ && row_[0]) ? std::stoi(row_[0]) : 0;

    std::cout << "dbLines:" << dbLines << std::endl;
    query_ = "SELECT COUNT(*) FROM Parking_Record;";
    if (mysql_query(sql_->my_, query_.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }
    res_ = mysql_store_result(sql_->my_);
    if (!res_)
    {
        std::cerr << "Store result failed: " << mysql_error(sql_->my_) << std::endl;
    }
    row_ = mysql_fetch_row(res_);
    int recordLines = (row_ && row_[0]) ? std::stoi(row_[0]) : 0;
    mysql_free_result(res_);

    bool isChanged;
    if (lines == dbLines && recordLines == totalLines)
    {
        isChanged = false;
        Json::Value root;
        Json::Value message2;
        Json::Value message3;
        Json::FastWriter w;
        root["func"] = 3;
        message2["isChanged"] = 0;
        root["message"] = message2;
        std::string content = w.write(root);
        std::string package = Encode(content);

        std::cout << content << std::endl;
        std::cout << package << std::endl;
        int n = write(sockfd_, package.c_str(), package.size());
        if (n < 0)
        {
            lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
            return;
        }
        return;
    }

    int newData = dbLines - lines;
    // int newData = 2;
    //  std::string query =
    //      "SELECT p.location, v.plate, pr.entry_time, pr.exit_time, pr.fee, pr.status "
    //      "FROM Parking_Record pr "
    //      "LEFT JOIN Vehicle v ON pr.vehicle_id = v.vehicle_id "
    //      "LEFT JOIN Parking_Spot p ON pr.spot_id = p.spot_id;";

    std::string nQuery = "SELECT p.record_id "
                         "FROM Payment p "
                         "ORDER BY p.payment_time DESC "
                         "LIMIT " +
                         std::to_string(newData) + ";";
    std::vector<int> recordIds;

    if (mysql_query(sql_->my_, nQuery.c_str()) == 0)
    {
        MYSQL_RES *res = mysql_store_result(sql_->my_);
        MYSQL_ROW row;

        while ((row = mysql_fetch_row(res)))
        {
            if (row[0])
            {
                int recordId = std::stoi(row[0]);
                recordIds.push_back(recordId);
            }
        }

        mysql_free_result(res);
    }
    else
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }

    for (auto i : recordIds)
    {
        std::cout << i << " ";
        i++;
    }

    std::string query =
        "SELECT ps.location, v.plate, pr.entry_time, pr.exit_time, pr.fee, pr.status "
        "FROM Parking_Record pr "
        "LEFT JOIN Vehicle v ON pr.vehicle_id = v.vehicle_id "
        "LEFT JOIN Parking_Spot ps ON pr.spot_id = ps.spot_id "
        "INNER JOIN ("
        "    SELECT p.record_id "
        "    FROM Payment p "
        "    ORDER BY p.payment_time DESC "
        "    LIMIT " +
        std::to_string(newData) +
        ") recent ON pr.record_id = recent.record_id;";

    if (mysql_query(sql_->my_, query.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    MYSQL_RES *res = mysql_store_result(sql_->my_);
    if (!res)
    {
        std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    MYSQL_ROW row;
    MYSQL_FIELD *fields = mysql_fetch_fields(res);
    int num_fields = mysql_num_fields(res);
    Json::Value result(Json::arrayValue);

    int count = 0;
    while ((row = mysql_fetch_row(res)))
    {
        Json::Value record;
        for (int i = 0; i < num_fields; ++i)
        {
            std::string key = fields[i].name;
            if (row[i])
                record[key] = row[i]; // 有值直接存
            else
                record[key] = Json::nullValue; // 无值用null
            count++;
        }
        result.append(record);
    }
    mysql_free_result(res);

    int gapN = recordLines - totalLines;
    std::string newDataquery =
        "SELECT p.location, v.plate, pr.entry_time, pr.exit_time, pr.fee, pr.status "
        "FROM Parking_Record pr "
        "LEFT JOIN Vehicle v ON pr.vehicle_id = v.vehicle_id "
        "LEFT JOIN Parking_Spot p ON pr.spot_id = p.spot_id "
        "ORDER BY pr.record_id DESC "
        "LIMIT " +
        std::to_string(gapN) + ";";
    if (mysql_query(sql_->my_, newDataquery.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    MYSQL_RES *res1 = mysql_store_result(sql_->my_);
    if (!res1)
    {
        std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
        return;
    }
    MYSQL_ROW row1;
    MYSQL_FIELD *fields1 = mysql_fetch_fields(res1);
    int num_fields1 = mysql_num_fields(res1);
    int count1 = 0;
    Json::Value newResult(Json::arrayValue);
    while ((row1 = mysql_fetch_row(res1)))
    {
        Json::Value record;
        for (int i = 0; i < num_fields1; ++i)
        {
            std::string key = fields1[i].name;
            if (row1[i])
                record[key] = row1[i]; // 有值直接存
            else
                record[key] = Json::nullValue; // 无值用null
            count1++;
        }
        newResult.append(record);
    }
    mysql_free_result(res1);

    std::cout << "result" << result << std::endl;
    std::cout << "newResult" << newResult << std::endl;
    Json::Value root;
    Json::Value message2;
    Json::Value message3;
    Json::FastWriter w;
    Json::Value array(Json::arrayValue);
    for (const auto &i : recordIds)
    {
        array.append(i);
    }
    root["func"] = 3;
    message2["messageArray"] = result;
    message2["newResult"] = newResult;
    // message2["func2"] = 1;
    message2["isChanged"] = 1;
    message2["recordIdsArray"] = array;
    root["message"] = message2;
    std::string content = w.write(root);
    std::string package = Encode(content);

    std::cout << content << std::endl;
    std::cout << package << std::endl;
    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
        return;
    }
}

void Task::payment(Json::Value message)
{
    int lines = message["lines"].asInt();
    std::cout << "lines:" << lines << std::endl;
    std::string query_ = "SELECT COUNT(*) FROM Payment;";
    if (mysql_query(sql_->my_, query_.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }

    MYSQL_RES *res_ = mysql_store_result(sql_->my_);
    if (!res_)
    {
        std::cerr << "Store result failed: " << mysql_error(sql_->my_) << std::endl;
    }

    MYSQL_ROW row_ = mysql_fetch_row(res_);
    int dbLines = (row_ && row_[0]) ? std::stoi(row_[0]) : 0;
    mysql_free_result(res_);
    std::cout << "dbLines:" << dbLines << std::endl;

    bool isChanged = true;
    if (lines != dbLines)
    {
        isChanged = true;
    }
    else
    {
        isChanged = false;
    }

    // std::string query = "SELECT p.payment_time, p.amount,v.plate,p.record_id "
    //                     "FROM Payment p "
    //                     "LEFT JOIN Parking_Record pr on pr.record_id = p.record_id "
    //                     "LEFT JOIN Vehicle v on v.vehicle_id = pr.vehicle_id;";
    if (!isChanged)
    {
        Json::Value root;
        Json::Value message2;
        Json::Value message3;
        Json::FastWriter w;
        root["func"] = 4;
        message2["isChanged"] = 0;
        message2["message2"] = message3;
        // message2["func2"] =1;
        root["message"] = message2;
        std::string content = w.write(root);
        std::string package = Encode(content);

        int n = write(sockfd_, package.c_str(), package.size());
        if (n < 0)
        {
            lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
            return;
        }
        return;
    }

    int num = dbLines - lines;
    std::string query = "SELECT p.payment_time, p.amount, v.plate, p.record_id "
                        "FROM Payment p "
                        "LEFT JOIN Parking_Record pr ON pr.record_id = p.record_id "
                        "LEFT JOIN Vehicle v ON v.vehicle_id = pr.vehicle_id "
                        "ORDER BY p.payment_time DESC "
                        "LIMIT " +
                        std::to_string(num) + ";";

    if (mysql_query(sql_->my_, query.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }
    MYSQL_RES *res = mysql_store_result(sql_->my_);
    if (!res)
    {
        std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
        return;
    }
    MYSQL_ROW row;
    MYSQL_FIELD *fields = mysql_fetch_fields(res);
    int num_fields = mysql_num_fields(res);
    Json::Value result(Json::arrayValue);

    int count = 0;
    while ((row = mysql_fetch_row(res)))
    {
        Json::Value record;
        for (int i = 0; i < num_fields; ++i)
        {
            std::string key = fields[i].name;
            if (row[i])
                record[key] = row[i]; // 有值直接存
            else
                record[key] = Json::nullValue; // 无值用null
            count++;
        }
        result.append(record);
    }
    mysql_free_result(res);
    std::cout << result << std::endl;
    Json::Value root;
    Json::Value message2;
    Json::Value message3;
    Json::FastWriter w;
    root["func"] = 4;
    message3["messageArray"] = result;
    message2["isChanged"] = 1;
    message2["message2"] = message3;
    // message2["func2"] =1;
    root["message"] = message2;
    std::string content = w.write(root);
    std::string package = Encode(content);

    // std::cout<<content<<std::endl;
    // std::cout<<package<<std::endl;
    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
        return;
    }
}

void Task::currentStatistic(Json::Value message)
{
    std::string query = "SELECT * FROM Statistics_View";
    if (mysql_query(sql_->my_, query.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    MYSQL_RES *res = mysql_store_result(sql_->my_);
    if (!res)
    {
        std::cerr << "Failed to get result: " << mysql_error(sql_->my_) << std::endl;
        return;
    }
    MYSQL_ROW row = mysql_fetch_row(res);
    if (!row)
    {

        std::cerr << "No data found in Statistics_View." << std::endl;
        return;
    }
    std::string stat_date = row[0] ? row[0] : "null";
    std::string entry_count = row[1] ? row[1] : "0";
    std::string exit_count = row[2] ? row[2] : "0";
    std::string total_income = row[3] ? row[3] : "0.00";
    std::string usage_rate = row[4] ? row[4] : "0.00";
    std::string reservation_cnt = row[5] ? row[5] : "0";
    std::string reservation_rt = row[6] ? row[6] : "0.00";
    mysql_free_result(res);
    // std::cout << "Stat Date        : " << stat_date << std::endl;
    // std::cout << "Entry Count      : " << entry_count << std::endl;
    // std::cout << "Exit Count       : " << exit_count << std::endl;
    // std::cout << "Total Income     : " << total_income << std::endl;
    // std::cout << "Usage Rate       : " << usage_rate << "%" << std::endl;
    // std::cout << "Reservation Count: " << reservation_cnt << std::endl;
    // std::cout << "Reservation Rate : " << reservation_rt << "%" << std::endl;
    Json::Value root;
    Json::Value message1;
    Json::Value message2;
    Json::FastWriter w;
    message2["stat_date"] = stat_date;
    message2["entry_count"] = entry_count;
    message2["exit_count"] = exit_count;
    message2["total_income"] = total_income;
    message2["usage_rate"] = usage_rate;
    message2["reservation_cnt"] = reservation_cnt;
    message2["reservation_rt"] = reservation_rt;
    message1["func2"] = 1;
    message1["message2"] = message2;
    root["func"] = 5;
    root["message"] = message1;

    std::string content = w.write(root);
    std::string package = Encode(content);

    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
        return;
    }
}

void Task::previousStatistic(Json::Value message)
{
    std::string date = message["date"].asString();
    std::string query = "SELECT stat_date FROM Daily_Statistics LIMIT 1";
    std::string stat_date;
    if (mysql_query(sql_->my_, query.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << ",at:" << __LINE__ << "\n";
        return;
    }
    MYSQL_RES *res = mysql_store_result(sql_->my_);
    if (!res)
    {
        std::cerr << "mysql_store_result failed: " << mysql_error(sql_->my_) << ", at: " << __LINE__ << "\n";
        return;
    }
    MYSQL_ROW row = mysql_fetch_row(res);
    if (row && row[0]) // row[0] 即 stat_date 字段的值
    {
        stat_date = row[0];
        // std::cout << "stat_date: " << stat_date << "\n";
    }
    else
    {
        std::cerr << "No result found or stat_date is null.\n";
    }

    bool b = isValidDate(stat_date, date);
    std::cout << b << std::endl;
    Json::Value root;
    Json::Value message1;
    Json::Value message2;
    Json::FastWriter w;
    if (!b)
    {
        message2["bool"] = 0;
    }
    else
    {
        message2["bool"] = 1;
        std::cout << "1111" << std::endl;
        std::string query = "SELECT * FROM Daily_Statistics WHERE stat_date = '" + date + "';";
        if (mysql_query(sql_->my_, query.c_str()))
        {
            std::cerr << "Query failed: " << mysql_error(sql_->my_) << ",at:" << __LINE__ << "\n";
        }
        MYSQL_RES *res = mysql_store_result(sql_->my_);
        if (!res)
        {
            std::cerr << "mysql_store_result failed: " << mysql_error(sql_->my_) << ", at: " << __LINE__ << "\n";
            return;
        }
        std::cout << "2222" << std::endl;
        MYSQL_ROW row = mysql_fetch_row(res);
        message2["stat_date"] = row[0] ? row[0] : "null";
        message2["entry_count"] = row[1] ? row[1] : "0";
        message2["exit_count"] = row[2] ? row[2] : "0";
        message2["total_income"] = row[3] ? row[3] : "0.00";
        message2["usage_rate"] = row[4] ? row[4] : "0.00";
        message2["reservation_cnt"] = row[5] ? row[5] : "0";
        message2["reservation_rt"] = row[6] ? row[6] : "0.00";
        std::cout << "3333" << std::endl;
        mysql_free_result(res);
    }

    message1["func2"] = 2;
    message1["message2"] = message2;
    root["func"] = 5;
    root["message"] = message1;
    std::string content = w.write(root);
    std::string package = Encode(content);
    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
        return;
    }
}

void Task::registe(Json::Value message)
{
    std::string password = message["password"].asString();
    std::string username = message["username"].asString();
    std::string plate = message["plate"].asString();
    std::string hashed = bcrypt::generateHash(password); // 哈希加密过的密码
    Json::Value root;
    Json::FastWriter w;

    std::string query2 = "SELECT 1 FROM users WHERE username = '" + username + "' LIMIT 1";
    if (mysql_query(sql_->my_, query2.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << "\n";
    }
    MYSQL_RES *res = mysql_store_result(sql_->my_);
    bool exists = (mysql_num_rows(res) > 0);
    if (exists) // 有重名
    {
        root["bool"] = 2;
        lg(Info, "registe:有重复用户名");
    }
    else // 无重名
    {
        std::string query = "INSERT INTO users (username, password, license_plate) VALUES ('" + username + "', '" + hashed + "', '" + plate + "')";
        int sql_n = mysql_query(sql_->my_, query.c_str());

        if (sql_n)
        {
            std::cerr << "Insert failed: " << mysql_error(sql_->my_) << std::endl;
            root["bool"] = 0;
        }
        else
        {
            root["bool"] = 1;
        }
    }

    std::string content = w.write(root);
    std::string package = Encode(content);

    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
        return;
    }
}

void Task::login(Json::Value message)
{
    std::string password = message["password"].asString();
    std::string username = message["username"].asString();

    MYSQL_RES *res;
    MYSQL_RES *res2;
    MYSQL_ROW row;
    MYSQL_ROW row2;
    Json::Value root;
    Json::FastWriter w;
    std::string query = "SELECT 1 FROM users WHERE username = '" + username + "' LIMIT 1";

    if (mysql_query(sql_->my_, query.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << "\n";
    }
    res = mysql_store_result(sql_->my_);
    bool exists = mysql_num_rows(res) > 0;
    root["plate"] = "";
    if (exists) // 存在这个用户
    {
        std::string query2 = "SELECT password FROM users WHERE username = '" + username + "'";

        if (mysql_query(sql_->my_, query2.c_str()))
        {
            std::cerr << "Query failed: " << mysql_error(sql_->my_) << "\n";
        }
        MYSQL_RES *res;
        MYSQL_ROW row;
        res = mysql_store_result(sql_->my_);
        std::string passwdInSQL;
        if ((row = mysql_fetch_row(res)))
        {
            passwdInSQL = row[0]; // 获取 password
            mysql_free_result(res);
        }

        if (bcrypt::validatePassword(password, passwdInSQL))
        {
            lg(Info, "login:密码正确");
            root["bool"] = 1;

            // 接下来取出车牌的值
            std::string query3 = "SELECT license_plate FROM users WHERE username = '" + username + "'";
            std::string plate;
            if (mysql_query(sql_->my_, query3.c_str()))
            {
                std::cerr << "Query failed: " << mysql_error(sql_->my_) << "\n";
            }
            res2 = mysql_store_result(sql_->my_);
            if ((row2 = mysql_fetch_row(res2)))
            {
                plate = row2[0];
                root["plate"] = plate;
                mysql_free_result(res2);
            }
        }
        else
        {
            lg(Info, "login:密码错误");
            root["bool"] = 0;
        }
    }
    else // 不存在用户
    {
        lg(Info, "login:不存在该用户名");
        root["bool"] = 2;
    }

    std::string content = w.write(root);
    std::string package = Encode(content);

    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
        return;
    }
}

void Task::reservation(Json::Value message)
{
    MYSQL_RES *res;
    MYSQL_ROW row;

    std::string plate = message["plate"].asString();
    std::string time = message["time"].asString();
    std::string user = message["user"].asString();

    std::string find_userId_query = "SELECT user_id FROM users WHERE username = '" + user + "';";
    if (mysql_query(sql_->my_, find_userId_query.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }

    res = mysql_store_result(sql_->my_);
    if (!res)
    {
        std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
    }
    int user_id = -1;
    if ((row = mysql_fetch_row(res)))
    {
        user_id = std::stoi(row[0]);
    }

    std::string plate_query = "SELECT vehicle_id FROM Vehicle WHERE plate = '" + plate + "';";
    if (mysql_query(sql_->my_, plate_query.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
    }
    res = mysql_store_result(sql_->my_);
    int vehicle_id = -1;
    if ((row = mysql_fetch_row(res)))
    {
        vehicle_id = std::stoi(row[0]); // 已存在，获取 vehicle_id
    }
    else
    {
        // 不存在，插入新记录
        std::string insert_sql = "INSERT INTO Vehicle (plate, status) VALUES ('" + plate + "', 'out');";
        if (mysql_query(sql_->my_, insert_sql.c_str()))
        {
            std::cerr << "Insert failed: " << mysql_error(sql_->my_) << std::endl;
        }
        // 获取新插入的 ID
        vehicle_id = mysql_insert_id(sql_->my_);
    }

    std::string location;
    int avaPortId = getAvailableSpot(location);
    std::string query = "INSERT INTO Reservation (vehicle_id, spot_id, start_time, user_id, status) VALUES (" +
                        std::to_string(vehicle_id) + ", " +
                        std::to_string(avaPortId) + ", '" +
                        time + "', " +
                        std::to_string(user_id) + ", 'available');";
    if (mysql_query(sql_->my_, query.c_str()))
    {
        std::cerr << "Insert failed: " << mysql_error(sql_->my_) << std::endl;
    }
    else
    {
        // std::cout << "Reservation inserted successfully." << std::endl;
        lg(Info, "Reservation inserted successfully,vehicle_id:%d,spot_id:%d,start_time%s,user_id:%d,status:%s", vehicle_id, avaPortId, time, user_id, "available");
    }

    std::string spot_query = "UPDATE Parking_Spot SET status = 'reserved' WHERE spot_id = " + std::to_string(avaPortId) + ";";
    if (mysql_query(sql_->my_, spot_query.c_str()))
    {
        std::cerr << "Update failed: " << mysql_error(sql_->my_) << std::endl;
    }
    else
    {
        // std::cout << "Spot status updated successfully." << std::endl;
        lg(Info, "Spot status updated successfully,spot_id:%d", avaPortId);
    }

    std::cout << "port_id: " << avaPortId << "location" << location << std::endl;
    mysql_free_result(res);

    Json::Value root;
    Json::FastWriter w;
    root["location"] = location;
    std::string content = w.write(root);
    std::string package = Encode(content);
    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
        return;
    }
}

// void Task::myreservation(Json::Value message)
// {
//     Json::Value result(Json::arrayValue);
//     MYSQL_RES *res;
//     MYSQL_ROW row;
//     std::string user = message["user"].asString();
//     std::string find_userId_query = "SELECT user_id FROM users WHERE username = '" + user + "';"; // 根据username获取user_id
//     if (mysql_query(sql_->my_, find_userId_query.c_str()))
//     {
//         std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
//     }

//     res = mysql_store_result(sql_->my_);
//     if (!res)
//     {
//         std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
//     }
//     int user_id = -1;
//     if ((row = mysql_fetch_row(res)))
//     {
//         user_id = std::stoi(row[0]);
//     }
//     // std::cout << user_id << std::endl;
//     //  获取 Reservation + Parking_Spot.location + Vehicle.plate
//     std::string query =
//         "SELECT r.reservation_id, r.vehicle_id, v.plate, r.spot_id, p.location, "
//         "r.start_time, r.user_id, r.status "
//         "FROM Reservation r "
//         "JOIN Parking_Spot p ON r.spot_id = p.spot_id "
//         "JOIN Vehicle v ON r.vehicle_id = v.vehicle_id "
//         "WHERE r.user_id = " +
//         std::to_string(user_id);

//     if (mysql_query(sql_->my_, query.c_str()) != 0)
//     {
//         std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
//     }

//     MYSQL_RES *res2 = mysql_store_result(sql_->my_);
//     if (!res2)
//     {
//         std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
//     }

//     MYSQL_ROW row1;
//     MYSQL_FIELD *fields = mysql_fetch_fields(res2);
//     int num_fields = mysql_num_fields(res2);

//     // 遍历所有行
//     while ((row1 = mysql_fetch_row(res2)))
//     {
//         Json::Value record;
//         for (int i = 0; i < num_fields; ++i)
//         {
//             std::string key = fields[i].name;
//             std::string value = row1[i] ? row1[i] : "null";
//             record[key] = value;
//         }
//         result.append(record);
//     }
//     std::cout<<result<<std::endl;
//     Json::FastWriter w;
//     std::string content = w.write(result);
//     std::string package = Encode(content);
//     std::cout<<package<<std::endl;
//     int n = write(sockfd_, package.c_str(), package.size());
//     if (n < 0)
//     {
//         lg(Warning, "write error, errno: %d,errstring:%d", errno, strerror(errno));
//         return;
//     }
// }

void Task::myreservation(Json::Value message)
{
    Json::Value result(Json::arrayValue);
    MYSQL_RES *res;
    MYSQL_ROW row;
    std::string user = message["user"].asString();

    // 查 user_id
    std::string find_userId_query = "SELECT user_id FROM users WHERE username = '" + user + "';";
    if (mysql_query(sql_->my_, find_userId_query.c_str()))
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    res = mysql_store_result(sql_->my_);
    if (!res)
    {
        std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    int user_id = -1;
    if ((row = mysql_fetch_row(res)))
    {
        user_id = std::stoi(row[0]);
    }
    mysql_free_result(res);

    if (user_id == -1)
    {
        std::cerr << "User not found!" << std::endl;
        return;
    }

    // 查 Reservation信息，并按reservation_id降序排列
    std::string query =
        "SELECT r.reservation_id, r.vehicle_id, v.plate, r.spot_id, p.location, "
        "r.start_time, r.user_id, r.status "
        "FROM Reservation r "
        "JOIN Parking_Spot p ON r.spot_id = p.spot_id "
        "JOIN Vehicle v ON r.vehicle_id = v.vehicle_id "
        "WHERE r.user_id = " +
        std::to_string(user_id) +
        " ORDER BY r.reservation_id DESC;"; // 降序

    if (mysql_query(sql_->my_, query.c_str()) != 0)
    {
        std::cerr << "Query failed: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    MYSQL_RES *res2 = mysql_store_result(sql_->my_);
    if (!res2)
    {
        std::cerr << "Failed to store result: " << mysql_error(sql_->my_) << std::endl;
        return;
    }

    MYSQL_ROW row1;
    MYSQL_FIELD *fields = mysql_fetch_fields(res2);
    int num_fields = mysql_num_fields(res2);

    int count = 0;
    int times = 6; // 在安卓端查看预约记录界面，只显示近五条，后续可能修改为滑到页面底自动再传输5条
    while ((row1 = mysql_fetch_row(res2)) && count < times)
    {
        Json::Value record;
        for (int i = 0; i < num_fields; ++i)
        {
            std::string key = fields[i].name;
            std::string value = row1[i] ? row1[i] : "null";
            record[key] = value;
        }
        result.append(record);
        count++;
    }

    mysql_free_result(res2);
    Json::FastWriter w;
    std::string content = w.write(result);
    std::string package = Encode(content);

    int n = write(sockfd_, package.c_str(), package.size());
    if (n < 0)
    {
        lg(Warning, "write error, errno: %d,errstring:%s", errno, strerror(errno));
        return;
    }
}
